package com.noble.glamour.wxapi;

import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;

import com.noble.glamour.module.logic.application.ModuleMgr;
import com.noble.glamour.module.logic.config.UrlParam;
import com.noble.glamour.module.logic.request.HttpResponse;
import com.noble.glamour.module.logic.request.RequestComplete;
import com.noble.library.third.ThirdConstant;
import com.noble.library.third.auth.OauthCallback;
import com.noble.library.third.auth.ThirdInfo;
import com.noble.library.log.PSP;
import com.tencent.mm.sdk.modelbase.BaseReq;
import com.tencent.mm.sdk.modelbase.BaseResp;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.IWXAPIEventHandler;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 微信回调类
 */
public class WXEntryActivity extends FragmentActivity implements IWXAPIEventHandler, OnKeyListener, RequestComplete {
    private IWXAPI mApi;
    private OauthCallback mOauthCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mApi = ModuleMgr.getAuthMgr().getWXApi();
        if (mApi == null) {
            finish();
            return;
        }
        mOauthCallback = ModuleMgr.getAuthMgr().getCallback();
        mApi.handleIntent(getIntent(), this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    @Override
    public void onReq(BaseReq arg0) {
        finish();
    }

    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    @Override
    public void onResp(BaseResp resp) {
        if (resp instanceof SendAuth.Resp) {    // 微信Oauth 认证返回
            SendAuth.Resp authRes = (SendAuth.Resp) resp;
            if (mOauthCallback != null && resp.checkArgs()) {
                switch (authRes.errCode) {
                    case BaseResp.ErrCode.ERR_OK:  // 拿到AccessToken
                        PSP.getInstance().put(ThirdConstant.WECHAT_CODE, authRes.code); // 保存code到本地
                        ModuleMgr.getLoginMgr().loadAccessToken(authRes.code, this);
                        break;

                    case BaseResp.ErrCode.ERR_USER_CANCEL:
                        mOauthCallback.onCancelled(ThirdConstant.WECHAT);
                        break;

                    case BaseResp.ErrCode.ERR_AUTH_DENIED:
                        mOauthCallback.onFailure(ThirdConstant.WECHAT, "User denied");
                        break;

                    default:
                        mOauthCallback.onError(ThirdConstant.WECHAT, new Exception(authRes.errStr));
                        break;
                }
            }
        }
        finish();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);

        mApi.handleIntent(intent, this);
    }

    @Override
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return false;
    }

    /**
     * 微信接口请求失败处理
     */
    private void error(Exception ex) {
        if (mOauthCallback != null) {
            mOauthCallback.onError(ThirdConstant.WECHAT, ex);
        }
    }

    /**
     * 向后台请求第三方登录状态回调
     */
    @Override
    public void onRequestComplete(HttpResponse response) {
        JSONObject jsonObject = response.getResponseJson();

        // 获取Token
        if (response.getUrlParam() == UrlParam.getWXAccessToken) {
            try {
                if (jsonObject.has("errcode")) {
                    String errcode = jsonObject.optString("errcode");
                    String errmsg = jsonObject.optString("errmsg");
                    error(new Exception("get access token error; error code = " + errcode + "; error msg = " + errmsg));
                    finish();
                } else {
                    String accessToken = jsonObject.getString("access_token");
                    String openid = jsonObject.getString("openid");
                    ModuleMgr.getLoginMgr().loadUserInfo(openid, accessToken, this);
                }
            } catch (JSONException e) {
                e.printStackTrace();
                finish();
            }
        }

        // 获取用户资料
        if (response.getUrlParam() == UrlParam.getWXUserInfo) {
            try {
                if (jsonObject.has("errcode")) {
                    String errcode = jsonObject.optString("errcode");
                    String errmsg = jsonObject.optString("errmsg");
                    error(new Exception("get user info error; error code = " + errcode + "; error msg = " + errmsg));
                } else {
                    ThirdInfo u = ThirdInfo.wechat(jsonObject);
                    if (u == null) {
                        error(new Exception("get user info error"));
                    } else {
                        if (mOauthCallback != null) {
                            u.setPlat(ThirdConstant.WECHAT);
                            mOauthCallback.onSuccess(ThirdConstant.WECHAT, u);
                        }
                    }
                    ModuleMgr.getLoginMgr().setThirdInfo(u);
                }
            } catch (Exception e) {
                error(new Exception("get access token error; return data: " + response.getResponseString()));
            }
            this.finish();
        }
    }
}